package Team.Yaohuo.controller;


import Team.Yaohuo.constant.JDYConstant;
import Team.Yaohuo.properties.WxProperties;
import Team.Yaohuo.utils.WxUtil;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@Slf4j
public class PushController {

    @Autowired
    private WxProperties wxProperties;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private HttpServletResponse httpServletResponse;


    private static final String MEG_PUSH_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send";

    /**
     * 已登录的情况下正常进行消息推送
     * @param message
     * @throws IOException
     */
    @PostMapping("/getMessage")
    public void getMessage(@RequestBody Map message) throws IOException {
        // 获取企业微信access_token
        String url_accessToken = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + wxProperties.getCorpid() + "&corpsecret=" + wxProperties.getCorpsecret();
        ResponseEntity<Map> result1 = restTemplate.exchange(url_accessToken, HttpMethod.GET, null, Map.class);
        String accessToken = (String) result1.getBody().get("access_token");
        Map data = (Map) message.get("data");
        // 发送方用户详情
        String content = (String) data.get("content");
        if (content == null || content.equals("")) {

            // 来源表单名称
            String entryName = (String) data.get("entry_name");
            // 提醒文字
            String notifyText = (String) data.get("notify_text");
            // 跳转url
            String url = (String) data.get("url");
            // 推送时间
            DateTime now = DateTime.now();
            String sendTime = now.toString("yyyy-MM-dd HH:ss:mm");
            // 审批方详情
            List<Map<String, Object>> to = (List<Map<String, Object>>) data.get("to");
            for (Map<String, Object> itemMap : to) {
                String username = (String) itemMap.get("username");
                switch (username) {
                    case "andy_wu":
                        username = "suming";
                        break;
                    case "liangyalin":
                        username = "liang";
                        break;
                    case "chenyingqing":
                        username = "liyingqing";
                        break;
                }
                Map<String, Object> meg = new HashMap<>();
                meg.put("touser", username);
                meg.put("msgtype", "textcard");
                meg.put("agentid", wxProperties.getAgentid());
                String finalUsername = username;
                meg.put("textcard", new HashMap<>() {
                    {
                        put("title", "[" + entryName + "]" + notifyText);
                        put("description",
                                "<div class=\"normal\" >业务类型：有新的流程待办事项</div>" +
                                        "<div class=\"normal\" >审批标题：" + entryName + "</div>" +
                                        "<div class=\"normal\" >申请时间：" + sendTime + "</div>"
                        );
                        put("url", "http://www.yaohuo.team/pushTwo?url="+ URLEncoder.encode(url) + "&username="+ finalUsername +"&state=jiandaoyun");
                        put("btntxt", "查看详细");
                    }
                });
                meg.put("enable_id_trans", 0);
                meg.put("enable_duplicate_check", 0);
                meg.put("duplicate_check_interval", 0);

                HttpEntity<Map<String, Object>> http = new HttpEntity<>(meg);
                ResponseEntity<Map> response = restTemplate.exchange(MEG_PUSH_URL + "?access_token=" + accessToken, HttpMethod.POST, http, Map.class);
                if (response.getBody() != null) {
                    Integer errcode = (Integer) response.getBody().get("errcode");
                    String msgid = (String) response.getBody().get("msgid");
                    if (errcode == 0) {
                        log.info("消息推送成功，当前megId为:{}", msgid);
                    } else {
                        log.error("消息推送失败，返回错误码为:{}, 请前往https://developer.work.weixin.qq.com/document/path/96213进行查看", errcode);
                    }
                }
            }
            return;
        }
        // 定义正则表达式模式，同时匹配报销人员名字和金额合计数字
        Pattern pattern = Pattern.compile("报销人员: ([^\\n]+)\\n金额合计: (\\d+)");
        Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            // 获取匹配到的报销人员名字
            String personName = matcher.group(1);
            // 获取匹配到的金额合计数字
            String amount = matcher.group(2);

            // 来源表单名称
            String entryName = (String) data.get("entry_name");
            // 提醒文字
            String notifyText = (String) data.get("notify_text");
            // 跳转url
            String url = (String) data.get("url");
            // 推送时间
            DateTime now = DateTime.now();
            String sendTime = now.toString("yyyy-MM-dd HH:ss:mm");
            // 审批方详情
            List<Map<String, Object>> to = (List<Map<String, Object>>) data.get("to");
            for (Map<String, Object> itemMap : to) {
                String username = (String) itemMap.get("username");

                switch (username) {
                    case "andy_wu":
                        username = "suming";
                        break;
                    case "liangyalin":
                        username = "liang";
                        break;
                    case "chenyingqing":
                        username = "liyingqing";
                        break;
                }
                Map<String, Object> meg = new HashMap<>();
                meg.put("touser", username);
                meg.put("msgtype", "textcard");
                meg.put("agentid", wxProperties.getAgentid());
                String finalUsername = username;
                meg.put("textcard", new HashMap<>() {
                    {
                        put("title", "[" + entryName + "]" + notifyText);
                        put("description",
                                "<div class=\"normal\" >业务类型：有新的流程待办事项</div>" +
                                        "<div class=\"normal\" >审批标题：" + entryName + "</div>" +
                                        "<div class=\"normal\" >审批内容：" + personName + "|" + amount + "</div>" +
                                        "<div class=\"normal\" >申请人：" + personName + "</span></div>" +
                                        "<div class=\"normal\" >申请时间：" + sendTime + "</div>"
                        );
                        put("url", "http://www.yaohuo.team/pushTwo?url="+ url +"&username="+ finalUsername +"&state=jiandaoyun");
                        put("btntxt", "查看详细");
                    }
                });
                meg.put("enable_id_trans", 0);
                meg.put("enable_duplicate_check", 0);
                meg.put("duplicate_check_interval", 0);

                HttpEntity<Map<String, Object>> http = new HttpEntity<>(meg);
                ResponseEntity<Map> response = restTemplate.exchange(MEG_PUSH_URL + "?access_token=" + accessToken, HttpMethod.POST, http, Map.class);
                if (response.getBody() != null) {
                    Integer errcode = (Integer) response.getBody().get("errcode");
                    String msgid = (String) response.getBody().get("msgid");
                    if (errcode == 0) {
                        log.info("消息推送成功，当前megId为:{}", msgid);
                    } else {
                        log.error("消息推送失败，返回错误码为:{}, 请前往https://developer.work.weixin.qq.com/document/path/96213进行查看", errcode);
                    }
                }

                httpServletResponse.sendRedirect(JDYConstant.ISS_JIANDAOYUN);
            }
        }
    }

    @GetMapping("/pushTwo")
    public String getMessageTwo(
            @RequestParam(name = "code", defaultValue = "") String code,
            @RequestParam(name = "state", defaultValue = "") String state,
            @RequestParam(name = "url", defaultValue = "") String url,
            @RequestParam(name = "username", defaultValue = "") String username
    ) throws IOException {
        HttpSession session = httpServletRequest.getSession();
        session.setAttribute("url", url);
        log.info("pushTwo接受的url为:{}", url);
        session.setAttribute("userId", username);
        if (code.equals("")&&!username.equals("")){
            code="goOn";//说明是消息推送来的
            switch (state) {
                case "tongtian":
                    try {
                        log.info("通天云code信息：" + code);
                        httpServletResponse.sendRedirect("http://140.143.157.251:12336/user_tongtian?code="+code+"&url="+ URLEncoder.encode(url)+"&username="+username);
//                        httpServletResponse.sendRedirect("http://140.143.157.251:12336/user_tongtian?code=" + code);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return "";
                case "chengyun":
                    try {
                        log.info("乘云code信息：" + code);
//                        httpServletResponse.sendRedirect("http://140.143.157.251:12336/user_chengyun?code="+code+"&url="+URLEncoder.encode(url));
                        httpServletResponse.sendRedirect("http://140.143.157.251:12336/user_chengyun?code=" + code+"&url="+URLEncoder.encode(url)+"&username="+username);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return "";
                case "huayu":
                    try {
                        log.info("华宇code信息：" + code);
//                        httpServletResponse.sendRedirect("http://140.143.157.251:12336/user_huayu?code="+code+"&url="+URLEncoder.encode(url));
                        httpServletResponse.sendRedirect("http://140.143.157.251:12336/user_huayu?code=" + code+"&url="+URLEncoder.encode(url)+"&username="+username);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return "";
                case "xiangyun":
                    try {
                        log.info("翔云code信息：" + code);
                        httpServletResponse.sendRedirect("http://140.143.157.251:12336/user_xiangyun?code=" + code+"&url="+URLEncoder.encode(url)+"&username="+username);
//                        httpServletResponse.sendRedirect("http://140.143.157.251:12336/user_xiangyun?code="+code+"&url="+URLEncoder.encode(url));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return "";
                case "jiandaoyun":
                    try {
                        log.info("简道云的code信息:{}", code);
                        //向简道云发起SSO请求
                        httpServletResponse.sendRedirect(
                                String.format(JDYConstant.ISS_JIANDAOYUN)
                        );
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }
        }
        return "";
    }
}